package com.vanke.agent.common;

import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.log4j.Logger;

import com.vanke.agent.Cfg;

/**
 * <b>function:</b> 消息接收者； 依赖hawtbuf-1.9.jar
 * 
 */
public class QueueReceiverTemplate {
	
	private static final Logger log=Logger.getLogger(QueueReceiverTemplate.class);
	// tcp 地址
	public static final String BROKER_URL = Cfg.get("mq.addr");
	// 目标，在ActiveMQ管理员控制台创建 http://localhost:8161/admin/queues.jsp
	public static final String TARGET = Cfg.get("mq.notice");
	
	private MessageListener msgListener;
 
	QueueConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, BROKER_URL);
    public void send() throws Exception {

        QueueConnection connection = null;
        QueueSession session = null;
        try {
            // 创建链接工厂
            // 通过工厂创建一个连接
            connection = factory.createQueueConnection();
            // 启动连接
            connection.start();
            // 创建一个session会话
            session = connection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建一个消息队列
            Queue queue = session.createQueue(TARGET);

            // 创建消息制作者
            javax.jms.QueueReceiver receiver = session.createReceiver(queue);
            receiver.setMessageListener(msgListener); 
            // 休眠100ms再关闭
//            Thread.sleep(1000 * 100); 
            // 提交会话
            session.commit();
        } catch (Exception e) {
        	log.info("接收队列消息失败:"+e.getStackTrace());
        } finally {
            // 关闭释放资源
            if (session != null) {
                session.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }

	public MessageListener getMsgListener() {
		return msgListener;
	}

	public void setMsgListener(MessageListener msgListener) {
		this.msgListener = msgListener;
	}
    
}
